
import { getDataByCodeApi, DataItem, DataSource } from '/@/api/system/data'
import { get, set } from 'lodash-es'

const requestQueue: Record<string, (() => void)[]> = {}
const dataCache: Record<string, DataSource> = {}
export function getDataItems(code: string, force: boolean = false): Promise<DataItem[]> {
  return new Promise(reslove => {

    const finalReslove = () => {
      const { dataItems } = get(dataCache, code, []);
      reslove(dataItems)
    }

    if (force || !dataCache[code]) {
      // 入队
      requestQueue[code] = requestQueue[code] || []
      requestQueue[code].unshift(finalReslove)

      // 只有一个成员时请求，后面的成员等待
      if (requestQueue[code].length === 1) {
        getDataByCodeApi(code).then(res => {
          if (res.succeeded && res.data.dataItems.length) {
            set(dataCache, code, res.data)
          }

          // 出队
          while (!!requestQueue[code].length) {
            try {
              requestQueue[code].pop()()
            } catch (err) {
              console.error(err)
            }
          }
        })
      }

    } else {
      finalReslove()
    }
  })

}


export function dataFormatter(value: any, code: string) {
  return new Promise(reslove => {
    getDataItems(code).then(items => {
      const item = items.find(s => s.value == value)
      if (item) {
        reslove(item.label)
      }
    })
  })
}

/**
 * 监听退出事件
 */
addEventListener('logout', e => {
  Object.keys(dataCache).forEach(k => {
    delete dataCache[k]
  })
})